package com.hzhc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.dto.RoleSelectVo;
import com.hzhc.entity.SysOrganizationRole;
import com.hzhc.entity.SysRole;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.mapper.SysOrganizationRoleMapper;
import com.hzhc.mapper.SysRoleMapper;
import com.hzhc.service.SysRoleService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.SysRoleVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色管理 服务实现类
 * @author yjt
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysRoleMapper roleMapper;
    private final SysOrganizationRoleMapper sysOrganizationRoleMapper;

    @Override
    public List<SysRoleVo> getRolePage(Page<SysRoleVo> page, SysRoleVo vo) {
        return baseMapper.selectRolePage(page, vo).getRecords();
    }

    @Override
    public ResultUtil<T> saveRole(SysRole role) {
        role.setCreateTime(LocalDateTime.now());
        ResultUtil<T> r = checkRole(role);
        if (!r.getCode().equals(ResultUtilCodeEnum.SUCCESS.getCode())) {
            return r;
        }
        boolean b = save(role);
        //组织角色新增
        if(StrUtil.isNotBlank(role.getOrganizationIds())){
            String[] organizationIds = role.getOrganizationIds().split(",");
            for (String organizationId : organizationIds) {
                SysOrganizationRole sysOrganizationRole = new SysOrganizationRole();
                sysOrganizationRole.setRoleId(role.getId());
                sysOrganizationRole.setOrganizationId(Long.valueOf(organizationId));
                sysOrganizationRoleMapper.insert(sysOrganizationRole);
            }
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updateRole(SysRole role) {
        ResultUtil<T> r = checkRole(role);
        if (!r.getCode().equals(ResultUtilCodeEnum.SUCCESS.getCode())) {
            return r;
        }
        boolean b = updateById(role);
        //组织角色删除
        sysOrganizationRoleMapper.delete(Wrappers.<SysOrganizationRole>lambdaUpdate()
                .eq(SysOrganizationRole::getRoleId,role.getId()));
        //组织角色新增
        if(StrUtil.isNotBlank(role.getOrganizationIds())){
            String[] organizationIds = role.getOrganizationIds().split(",");
            for (String organizationId : organizationIds) {
                SysOrganizationRole sysOrganizationRole = new SysOrganizationRole();
                sysOrganizationRole.setRoleId(role.getId());
                sysOrganizationRole.setOrganizationId(Long.valueOf(organizationId));
                sysOrganizationRoleMapper.insert(sysOrganizationRole);
            }
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> deleteRole(SysRole role) {
        boolean b = baseMapper.deleteRole(role);
        sysOrganizationRoleMapper.delete(Wrappers.<SysOrganizationRole>lambdaUpdate()
                .eq(SysOrganizationRole::getRoleId,role.getId()));
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }


    @Override
    public ResultUtil<T> checkRole(SysRole role) {
        int i = count(Wrappers.<SysRole>lambdaQuery()
                .eq(SysRole::getName, role.getName())
                //.eq(SysRole::getSystemId, role.getSystemId())
                .ne(role.getId() != null, SysRole::getId, role.getId()));
        return i > 0 ? ResultUtil.build(ResultUtilCodeEnum.ROLE_NAME_EXIST) : ResultUtil.ok();
    }

    @Override
    public List<RoleSelectVo> getAllRoleByUserIdList(SysRoleVo vo) {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<SysRole>();
        if (StrUtil.isNotBlank(vo.getName())) {
            queryWrapper.like(SysRole::getName, vo.getName());
        }
        if(vo.getOrganizationId()!=null){
            List<Long> roleIds = new ArrayList<>();
            List<SysOrganizationRole> sysOrganizationRoles = sysOrganizationRoleMapper.selectList(Wrappers.<SysOrganizationRole>lambdaQuery()
                    .eq(SysOrganizationRole::getOrganizationId, vo.getOrganizationId()));
            if(!sysOrganizationRoles.isEmpty()){
                roleIds = sysOrganizationRoles.stream().map(SysOrganizationRole::getRoleId).distinct().collect(Collectors.toList());
            }
            queryWrapper.in(SysRole::getId,roleIds);
        }
        List<SysRole> list = baseMapper.selectList(queryWrapper);
        List<RoleSelectVo> volist = new ArrayList<RoleSelectVo>();
        for (SysRole role : list) {
            RoleSelectVo rvo = new RoleSelectVo();
            rvo.setId(role.getId());
            rvo.setName(role.getName());
            rvo.setValue(role.getId().toString());
            if(!role.getStatus()){
                rvo.setDisabled("true");
            }
            volist.add(rvo);
        }
        return volist;
    }

    @Override
    public ResultUtil<T> getRoleCode(SysRole sysRole) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",sysRole.getCode());
        if(sysRole.getId()!=null){
            queryWrapper.ne("id",sysRole.getId());
        }
        if(sysRole.getCodeSource()!=null){
            queryWrapper.eq("code_source",sysRole.getCodeSource());
        }
        SysRole sysRoles = baseMapper.selectOne(queryWrapper);
        if(sysRoles != null){
            return ResultUtil.build(ResultUtilCodeEnum.SYSROLE_CODE);
        }else{
            return ResultUtil.ok();
        }
    }

    @Override
    public ResultUtil<T> selectRoleCode(String code) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",code);
        SysRole sysRole = baseMapper.selectOne(queryWrapper);
        if(sysRole == null){
            return ResultUtil.build(ResultUtilCodeEnum.SYSROLE_NO_CODE);
        }else{
            return ResultUtil.ok();
        }
    }

    @Override
    public ResultUtil<T> selectRoleCode(String type, String code) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",code);
        queryWrapper.eq("code_source",type);
        SysRole sysRole = baseMapper.selectOne(queryWrapper);
        if(sysRole == null){
            return ResultUtil.build(ResultUtilCodeEnum.SYSROLE_NO_CODE);
        }else{
            return ResultUtil.ok();
        }
    }

    @Override
    public List<SysRole> getRoleList(SysRole role) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<SysRole>();
        if(StrUtil.isNotBlank(role.getName())){
            queryWrapper.like("name",role.getName());
        }
        return roleMapper.selectList(queryWrapper);
    }

}
